package dynamic.ibatis.scripting.xmltags;

import dynamic.ibatis.builder.DSqlSourceBuilder;
import dynamic.ibatis.mapping.DBoundSql;
import dynamic.ibatis.mapping.DSqlSource;
import dynamic.ibatis.session.DConfiguration;


/**
 * @author Clinton Begin
 */
public class DDynamicSqlSource implements DSqlSource {

    private final DConfiguration configuration;
    private final SqlNode rootSqlNode;

    public DDynamicSqlSource(DConfiguration configuration, SqlNode rootSqlNode) {
        this.configuration = configuration;
        this.rootSqlNode = rootSqlNode;
    }

    @Override
    public DBoundSql getBoundSql(Object parameterObject) {
        DynamicContext context = new DynamicContext(configuration, parameterObject);
        rootSqlNode.apply(context);
        DSqlSourceBuilder sqlSourceParser = new DSqlSourceBuilder(configuration);
        Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
        DSqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
        DBoundSql boundSql = sqlSource.getBoundSql(parameterObject);
        context.getBindings().forEach(boundSql::setAdditionalParameter);
        return boundSql;
    }

}
